package com.yqr.common.config;

import com.yqr.common.exception.ServiceException;
import com.yqr.common.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * app全局异常处理
 */
@ControllerAdvice
@Slf4j
@ConditionalOnClass({HttpServletRequest.class})
public class GlobalExceptionHandler {

    /**
     * 业务异常处理
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = ServiceException.class)
    public R myErrorHandler(ServiceException e, HttpServletRequest req, HttpServletResponse response) {
        log.error("业务异常拦截 path={} params={} 异常msg：{}", req.getRequestURL().toString(), req.getParameterMap(), e.getMessage());
        // 自定义错误码返回
        if (0 != e.getErrorType()) {
            return R.fail(e.getErrorType(),e.getMessage());
        }
        return R.fail(e.getMessage());
    }

    /**
     * SSO 异常处理
     *
     * @param e
     * @return
     */
//    @ResponseBody
//    @ExceptionHandler(value = SsoException.class)
//    public ModelAndView ssoHandler(SsoException e, HttpServletRequest req, HttpServletResponse response) {
//        log.error("SSO 异常拦截 path={} params={} 异常msg：{}", req.getRequestURL().toString(), req.getParameterMap(), e.getMessage());
//        Res res = new Res(Res.Code.SESSION_INVALID.value(), e.getMessage());
//        return res.toJSONView(req, response);
//    }

    /**
     * 全局异常捕捉处理
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public R errorHandler(Exception e, HttpServletRequest req, HttpServletResponse response) {
        log.error("全局异常拦截 path={} params={}", req.getRequestURL().toString(), req.getParameterMap());
        log.error("全局异常拦截 异常信息", e);
        return R.fail("服务器开小差了");
    }
    
    /**
     * 全局异常捕捉处理
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
    public R errorHandler1(Exception e, HttpServletRequest req, HttpServletResponse response) {
        log.error("全局异常拦截 path={} params={}", req.getRequestURL().toString(), req.getParameterMap());
        log.error("全局异常拦截 异常信息", e);
        return R.fail("请输入有效的数据");
    }
    
    
}
